<template>
  <div>
    <el-upload
      v-show="!isShow"
      :class="['avatar-uploader',]"
      action="#"
      :http-request="onRequest"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-exceed="onExceed"
      :limit="limit"
      list-type="picture-card"
      :file-list="fileList"
      accept="image/png, image/jpeg, image/gif"
      :before-upload="beforeUpload"
    >
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
      <i class="el-icon-plus avatar-uploader-icon" />
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="isShow" type="circle" :percentage="percentage" />
    <el-dialog
      title="头像"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img :src="imageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID50f5E6h3VhcGelbATVGkzyg7HAn9E3aq',
  SecretKey: '0kDPJwJQJxLTKuEH3YliOmunPkobdS0H'
})
console.log(cos)
export default {
  props: {
    limit: {
      type: Number,
      default: 0 // 0代表可以无限传
    }
  },
  data() {
    return {
      imageUrl: '',
      fileList: [],
      dialogVisible: false,
      maxSize: 2 * 1024 * 1024,
      isShow: false,
      percentage: 0
    }
  },
  created() {

  },

  methods: {
    onRequest(data) {
      this.isShow = true
      console.log(data.file)
      this.id = setInterval(() => {
        if (this.percentage < 97) {
          this.percentage++
        } else {
          clearInterval(this.id)
        }
      }, 800)
      // 选择完图片开始上传
      cos.putObject({
        Bucket: 'hrsaas-1308960807', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: progressData => {
          // console.log(JSON.stringify(progressData))
          if (progressData.percent === 1) {
            this.percentage = 100
            clearInterval(this.id)
            setTimeout(() => {
              this.isShow = false
            }, 500)
          }
        }
      }, (err, data) => {
        // console.log(err || data)
        if (err) {
          this.$message.error('网络错误，上传失败！')
          this.isShow = false
          this.fileList.splice(this.fileList.length - 1)
        }
        if (!err && data.statusCode === 200) {
          this.$message.success('图片上传成功！')
          this.fileList[this.fileList.length - 1].url = 'https://' + data.Location
          this.$emit('on-success', this.fileList)
        }
      })
    },
    // 点击预览
    onPreview(file) {
      this.imageUrl = file.url
      this.dialogVisible = true
    },
    // 点击删除
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 文件上传之前，判断文件类型大小是否达标
    beforeUpload(file) {
      console.log(file)
      const imgArr = ['image/png', 'image/jpeg', 'image/gif']
      if (!imgArr.includes(file.type)) {
        this.$message('图片格式不正确！')
        return false
      }
      if (file.size > this.maxSize) {
        this.$message('图片过大！')
        return false
      }
    },
    // 文件改变
    onChange(file, fileList) {
      this.fileList = fileList
    },
    onExceed() {
      this.$message.warning('最多只能上传' + this.limit + '张图片')
    }
  }
}
</script>

<style lang='scss'>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
</style>
